<template>
  <div id="role">
    <div class="header-box coll">
      <div class="form-flex">
        <div class="form-item">
          <div class="label">角色名称</div>
          <el-input
            size="default"
            v-model.trim="query.role_name"
            style="margin-right: 10px"
            clearable
            placeholder="请输入搜索的内容"
          ></el-input>
        </div>
        <div class="form-item">
          <el-button type="primary" size="default" @click="onSeach">查询</el-button>
          <el-button type="primary" size="default" @click="addRow">新增角色</el-button>
        </div>
      </div>
    </div>
    <div class="table-box coll">
      <el-table
        ref="workbenchTable"
        :height="state.tableHeight"
        :data="state.tableData"
        tooltip-effect="dark"
        empty-text="暂无数据"
        style="width: 100%"
        :header-cell-style="{
          textAlign: 'center',
          backgroundColor: '#f5f7fa'
        }"
        :cell-style="{ textAlign: 'center' }"
        :row-style="{ height: '80px' }"
      >
        <el-table-column type="selection" width="60" fixed />
        <el-table-column label="序号" width="60">
          <template #default="scope">
            {{ scope.$index + 1 + (query.page - 1) * query.pageSize }}
          </template>
        </el-table-column>
        <el-table-column label="角色名称" min-width="120px" prop="role_name" />
        <el-table-column label="角色值" show-overflow-tooltip prop="role_value" />
        <el-table-column label="状态" min-width="120px" prop="role_status">
          <template #default="scope">
            <el-switch
              v-model="scope.row.role_status"
              inline-prompt
              active-text="已启用"
              inactive-text="已禁用"
              width="70px"
              @change="onChange(scope.row.role_status, scope.$index)"
            />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" min-width="120px" prop="create_time" />
        <el-table-column label="备注" min-width="220px" prop="remark" />
        <el-table-column label="操作" min-width="140px">
          <template #default="scope">
            <el-button size="small" type="primary" @click="editRow(scope.row)">修改角色</el-button>
            <el-button size="small" type="danger" @click="removeRole(2, scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- <div class="pagination">
        <el-pagination
          v-model:currentPage="query.page"
          v-model:page-size="query.pageSize"
          :page-sizes="[5, 20, 50, 100, 300]"
          background
          layout="sizes,prev, pager, next"
          :total="state.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
          <span style="margin-right: 5px">当前共{{ state.total }}条</span>
        </el-pagination>
      </div> -->
    </div>
    <el-drawer
      ref="drawerRef"
      v-model="addDialog"
      :title="tabRole ? '修改角色' : '新增角色'"
      direction="rtl"
      custom-class="demo-drawer"
      @close="treeClose"
    >
      <div class="demo-drawer__content">
        <el-form :model="form" ref="ruleFormRef" status-icon :rules="rules" class="demo-ruleForm">
          <el-form-item label="角色名称" :label-width="formLabelWidth" prop="role_name">
            <el-input v-model="form.role_name" autocomplete="off" />
          </el-form-item>
          <el-form-item label="角色值" :label-width="formLabelWidth" prop="role_value">
            <el-input v-model="form.role_value" autocomplete="off" />
          </el-form-item>
          <el-form-item label="状态" :label-width="formLabelWidth">
            <el-switch
              v-model="form.role_status"
              inline-prompt
              active-text="已启用"
              inactive-text="已禁用"
              width="70px"
            />
          </el-form-item>
          <el-form-item label="备注" :label-width="formLabelWidth">
            <el-input v-model="form.remark" type="textarea" />
          </el-form-item>
          <el-form-item label="菜单分配" :label-width="formLabelWidth">
            <el-tree
              v-if="!tabRole"
              ref="treeRef"
              show-checkbox
              :default-expand-all="false"
              :data="state.menus"
              highlight-current
              node-key="id"
              :props="defaultProps"
              @check-change="treeChange"
            />
            <el-tree
              v-else
              ref="treeRef"
              :default-checked-keys="state.menuIds"
              show-checkbox
              :default-expand-all="false"
              :data="state.menus"
              highlight-current
              node-key="id"
              :props="defaultProps"
              @check-change="treeChange"
            />
          </el-form-item>
        </el-form>
        <div class="demo-drawer__footer">
          <el-button @click="treeClose(ruleFormRef)">取消</el-button>
          <el-button type="primary" @click="addRole(ruleFormRef)">{{ tabRole ? ' 修改' : '确认' }}</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, onMounted, getCurrentInstance, ref } from 'vue'
  import { ElDrawer, ElMessage, ElNotification, FormRules, ElTree, FormInstance } from 'element-plus'
  import { getTableHeight } from '@/hooks/utils'
  import { role } from '@/network/model/cartoonModel'
  // @ts-ignore
  const { proxy } = getCurrentInstance()
  const api = proxy.$api
  const form = reactive({
    role_name: '',
    role_value: '',
    role_status: true,
    remark: '',
    menus: ''
  })
  const treeRef = ref<InstanceType<typeof ElTree>>()
  const addDialog = ref(false)
  const tabRole = ref(false)
  const formLabelWidth = '80px'
  const query = reactive({
    role_name: '',
    page: 1,
    pageSize: 20
  })
  interface Tree {
    id: number
    label: string
    children?: Tree[]
  }
  const defaultProps = {
    children: 'children',
    label: 'name'
  }
  const state = reactive({
    tableHeight: 0,
    tableData: [],
    total: 0,
    menus: [],
    menuIds: [] as any[],
    id: 0 //角色id
  })
  const rules = reactive<FormRules>({
    role_name: [{ required: true, message: '角色名不能为空', trigger: 'blur' }],
    role_value: [{ required: true, message: '角色值不能为空', trigger: 'blur' }]
  })
  const ruleFormRef = ref<FormInstance>()
  onMounted(() => {
    state.menus = JSON.parse(localStorage.getItem('MENUS'))
    state.tableHeight = getTableHeight(200)
    onSeach()
  })
  async function onSeach() {
    const res = await api.getRoles(query)
    if (res.code == 200) {
      state.tableData = res.data.data
      state.total = res.data.total
      state.tableData.forEach((item) => {
        item.role_status = item.role_status == 0 ? true : false
      })
      console.log(state.tableData, state.total)
    }
  }
  const handleSizeChange = (val: number) => {
    // console.log(`${val} items per page`)
    query.page = 1
    query.pageSize = val
    onSeach()
  }
  const handleCurrentChange = (val: number) => {
    query.page = val
    onSeach()
  }
  function treeChange() {
    state.menuIds = treeRef.value!.getCheckedKeys(false)
    console.log(form.menus)
  }
  // 改变状态
  async function onChange(val: Boolean, index: number) {
    console.log(val, index)
    const item: role = state.tableData[index]
    item.role_status = item.role_status ? 0 : 1
    await api.editRole(item)
    await onSeach()
  }
  // 取消操作
  function treeClose(formEl: FormInstance | undefined) {
    addDialog.value = false
    tabRole.value = false
    treeRef.value!.setCheckedKeys([], false)
    if (!formEl) return
    formEl.resetFields()
  }
  // 添加角色/修改角色
  async function addRole(formEl: FormInstance | undefined) {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
      if (valid) {
        form.menus = state.menuIds.join(',')
        let res = null
        if (tabRole.value) {
          form.id = state.id
          res = await api.editRole(form)
        } else {
          delete form.id
          res = await api.addRole(form)
        }
        if (res.code == 200) {
          ElNotification({
            title: '成功',
            message: res.msg,
            type: 'success'
          })
          treeClose(ruleFormRef.value)
          onSeach()
        } else {
          console.log(res.msg)
          ElNotification({
            title: '失败',
            message: res.msg,
            type: 'error'
          })
        }
      } else {
        console.log('error submit!', fields)
      }
    })
  }
  // 批量删除
  /**
   * @param type 1:批量删除 2:删除
   */
  async function removeRole(type: number, id: string = '') {
    let ids: any = []
    // if (type == 1) {
    //   if (multipleSelection.value.length == 0) {
    //     return ElMessage.warning('请选择要删除的信息')
    //   }
    //   multipleSelection.value.forEach((item) => {
    //     ids.push(item.id)
    //   })
    // } else {
    ids = id
    // }
    // console.log(ids, multipleSelection.value, 'multipleSelection.value')

    try {
      const res = await api.removeRole({ ids: ids.toString() })
      console.log(res, 'res')
      if (res.code == 200) {
        ElMessage.success(res.msg)
        onSeach()
      } else {
        ElMessage.error(res.msg)
      }
    } catch (error) {
      console.log(error)
      ElMessage.error('删除失败')
    }
  }
  // 打开添加角色
  function addRow() {
    addDialog.value = true
    tabRole.value = false
    form.remark = ''
    form.role_name = ''
    form.role_value = ''
    form.menus = ''
  }
  // 修改角色配置
  async function editRow(item: any) {
    tabRole.value = true
    addDialog.value = true
    form.role_name = item.role_name
    form.role_value = item.role_value
    form.role_status = item.role_status
    form.remark = item.remark
    state.id = item.id
    state.menuIds = item.menus?.split(',')
    // console.log(state.menuIds, '==>')
  }
</script>

<style scoped lang="less" src="./css/role.less"></style>
